<template>
  <div class="h-screen bg-gradient-to-br from-gray-50 to-gray-100 flex flex-col">
    <!-- 页面头部 -->
    <header class="bg-white/95 backdrop-blur-sm shadow-sm border-b border-gray-200/50 flex-shrink-0 relative z-40">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between h-16">
          <!-- 左侧：标题和返回按钮 -->
          <div class="flex items-center space-x-4">
            <button 
              @click="$router.back()"
              class="p-2 hover:bg-gray-100 rounded-lg transition-colors"
            >
              <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
              </svg>
            </button>
            <div class="flex items-center space-x-3">
              <div class="w-10 h-10 bg-gradient-to-br from-purple-500 to-pink-500 rounded-xl flex items-center justify-center shadow-lg">
                <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                </svg>
              </div>
              <div>
                <h1 class="text-xl font-bold text-gray-900">AI智能助手</h1>
                <p class="text-sm text-gray-500">与AI进行智能对话，获得编程帮助</p>
              </div>
            </div>
          </div>

          <!-- 右侧：模型选择和设置 -->
          <div class="flex items-center space-x-4">
            <!-- 历史面板切换按钮 -->
            <button 
              @click="toggleHistory"
              class="p-2 hover:bg-gray-100 rounded-lg transition-colors"
              :title="showHistory ? '隐藏历史' : '显示历史'"
            >
              <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
              </svg>
            </button>

            <!-- 模型选择 -->
            <div class="flex items-center space-x-2">
              <label class="text-sm font-medium text-gray-700">模型:</label>
              <div class="relative">
                <button
                  type="button"
                  class="px-3 py-2 bg-white border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-purple-500 focus:border-transparent transition-all text-left w-40"
                  @click="modelOpen = !modelOpen"
                >
                  {{ getCurrentModelName() }}
                  <span class="float-right text-gray-400">▼</span>
                </button>
                <ul
                  v-if="modelOpen"
                  class="absolute z-50 mt-2 w-40 bg-white rounded-lg border border-gray-200 shadow-lg overflow-hidden"
                >
                  <li
                    v-for="model in AI_MODELS"
                    :key="model.value"
                    class="px-3 py-2 cursor-pointer hover:bg-pink-500 hover:text-white text-sm"
                    @click="selectedModel = model.value; modelOpen = false"
                  >
                    {{ model.label }}
                  </li>
                </ul>
              </div>
            </div>

            <!-- 新建对话按钮 -->
            <button 
              @click="startNewChat"
              class="px-4 py-2 bg-gradient-to-r from-purple-500 to-pink-500 text-white rounded-lg text-sm font-medium hover:from-purple-600 hover:to-pink-600 transition-all transform hover:scale-105 shadow-lg"
            >
              <svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
              </svg>
              新建对话
            </button>
          </div>
        </div>
      </div>
    </header>

    <!-- 主要内容区 -->
    <main class="flex-1 px-4 sm:px-6 lg:px-8 py-6 overflow-hidden">
      <div class="flex gap-4 h-full">
        <!-- 左侧：对话历史 -->
        <aside 
          v-show="showHistory"
          class="w-64 bg-white/95 backdrop-blur-sm rounded-2xl shadow-lg border border-gray-200/50 flex flex-col transition-all duration-300"
        >
          <!-- 历史标题 -->
          <div class="p-3 border-b border-gray-200/50 flex-shrink-0">
            <div class="flex items-center justify-between">
              <h2 class="text-base font-semibold text-gray-900 flex items-center">
                <svg class="w-4 h-4 mr-2 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                历史
              </h2>
              <button 
                @click="toggleHistory"
                class="p-1 hover:bg-gray-100 rounded transition-colors"
              >
                <svg class="w-4 h-4 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
              </button>
            </div>
          </div>

          <!-- 历史列表 -->
          <div class="flex-1 overflow-y-auto p-3">
            <div v-if="sessions.length === 0" class="text-center py-6">
              <svg class="w-8 h-8 mx-auto text-gray-300 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
              </svg>
              <p class="text-gray-500 text-xs">暂无历史</p>
            </div>
            <div v-else class="space-y-1">
              <div 
                v-for="session in sessions" 
                :key="session.id"
                @click="loadSession(session.id)"
                :class="[
                  'p-2 rounded-lg cursor-pointer transition-all duration-200 group',
                  currentSessionId === session.id 
                    ? 'bg-gradient-to-r from-purple-500 to-pink-500 text-white shadow-md' 
                    : 'bg-gray-50 hover:bg-gray-100 text-gray-700'
                ]"
              >
                <div class="flex items-start justify-between">
                  <div class="flex-1 min-w-0">
                    <h3 class="font-medium text-xs truncate">{{ session.title }}</h3>
                    <p class="text-xs mt-1 opacity-75">{{ formatTime(session.updated_at) }}</p>
                  </div>
                  <button 
                    @click.stop="deleteSession(session.id)"
                    :class="[
                      'ml-1 p-1 rounded opacity-0 group-hover:opacity-100 transition-all',
                      currentSessionId === session.id 
                        ? 'hover:bg-white/20' 
                        : 'hover:bg-red-100 text-red-500'
                    ]"
                  >
                    <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                    </svg>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </aside>

        <!-- 右侧：对话区域 -->
        <div class="flex-1 bg-white/95 backdrop-blur-sm rounded-2xl shadow-lg border border-gray-200/50 flex flex-col">
          <!-- 对话内容 -->
          <div class="flex-1 overflow-y-auto p-6">
            <div v-if="messages.length === 0" class="flex flex-col items-center justify-center h-full text-center">
              <div class="w-20 h-20 bg-gradient-to-br from-purple-100 to-pink-100 rounded-full flex items-center justify-center mb-6">
                <svg class="w-10 h-10 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
                </svg>
              </div>
              <h3 class="text-xl font-semibold text-gray-900 mb-2">开始与AI对话</h3>
              <p class="text-gray-500 mb-6 max-w-md">我是你的AI编程助手，可以帮你解答编程问题、代码审查、算法思路等。有什么问题尽管问我吧！</p>
              
              <!-- 快捷问题 -->
              <div class="grid grid-cols-1 md:grid-cols-2 gap-3 max-w-2xl">
                <button 
                  v-for="suggestion in quickSuggestions"
                  :key="suggestion"
                  @click="sendQuickMessage(suggestion)"
                  class="p-3 text-left bg-gray-50 hover:bg-gray-100 rounded-xl transition-colors text-sm text-gray-700"
                >
                  {{ suggestion }}
                </button>
              </div>
            </div>

            <div v-else class="space-y-6">
              <div 
                v-for="message in messages" 
                :key="message.id"
                :class="[
                  'flex',
                  message.role === 'user' ? 'justify-end' : 'justify-start'
                ]"
              >
                <div 
                  :class="[
                    'max-w-3xl px-6 py-4 rounded-2xl shadow-sm',
                    message.role === 'user' 
                      ? 'bg-gradient-to-r from-purple-500 to-pink-500 text-white' 
                      : 'bg-gray-50 text-gray-900 border border-gray-200'
                  ]"
                >
                  <div class="flex items-start space-x-3">
                    <!-- AI头像 -->
                    <div v-if="message.role === 'assistant'" class="w-8 h-8 bg-gradient-to-br from-purple-400 to-pink-400 rounded-full flex items-center justify-center flex-shrink-0 mt-1">
                      <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                      </svg>
                    </div>
                    
                    <!-- 消息内容 -->
                    <div class="flex-1">
                      <p class="whitespace-pre-wrap leading-relaxed">{{ message.content }}</p>
                      <div class="flex items-center justify-between mt-2 text-xs opacity-75">
                        <span>{{ formatTime(message.created_at) }}</span>
                        <span v-if="message.tokens > 0">{{ message.tokens }} tokens</span>
                      </div>
                    </div>

                    <!-- 用户头像 -->
                    <div v-if="message.role === 'user'" class="w-8 h-8 bg-gradient-to-br from-blue-400 to-cyan-400 rounded-full flex items-center justify-center flex-shrink-0 mt-1">
                      <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                      </svg>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 加载状态 -->
              <div v-if="isLoading" class="flex justify-start">
                <div class="max-w-3xl px-6 py-4 bg-gray-50 rounded-2xl border border-gray-200 shadow-sm">
                  <div class="flex items-center space-x-3">
                    <div class="w-8 h-8 bg-gradient-to-br from-purple-400 to-pink-400 rounded-full flex items-center justify-center">
                      <svg class="w-4 h-4 text-white animate-pulse" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                      </svg>
                    </div>
                    <div class="flex space-x-1">
                      <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                      <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.1s"></div>
                      <div class="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style="animation-delay: 0.2s"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="p-6 border-t border-gray-200/50 bg-gray-50/50 flex-shrink-0">
            <div class="flex space-x-4">
              <div class="flex-1 relative">
                <textarea
                  v-model="inputMessage"
                  @keydown.enter.exact.prevent="sendMessage"
                  @keydown.enter.shift.exact="inputMessage += '\n'"
                  placeholder="输入你的问题... (Enter发送，Shift+Enter换行)"
                  class="w-full px-4 py-3 bg-white border border-gray-300 rounded-xl text-sm text-gray-900 placeholder-gray-500 focus:ring-2 focus:ring-purple-500 focus:border-transparent transition-all resize-none"
                  rows="3"
                  :disabled="isLoading"
                />
              </div>
              <button 
                @click="sendMessage"
                :disabled="!inputMessage.trim() || isLoading"
                class="px-6 py-3 bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-xl text-sm font-medium transition-all shadow-lg hover:shadow-xl transform hover:scale-105 disabled:transform-none flex items-center space-x-2"
              >
                <svg v-if="isLoading" class="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                </svg>
                <svg v-else class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>
                </svg>
                <span>发送</span>
              </button>
            </div>
            
            <!-- 输入提示 -->
            <div class="flex items-center justify-between mt-3 text-xs text-gray-500">
              <div class="flex items-center space-x-4">
                <span>当前模型: {{ getCurrentModelName() }}</span>
                <span v-if="currentSessionId">会话ID: {{ currentSessionId }}</span>
              </div>
              <div class="flex items-center space-x-2">
                <span>Enter发送</span>
                <span>•</span>
                <span>Shift+Enter换行</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { aiApi, type AIChatSession, type AIChatMessage, AI_MODELS } from '@/api/ai'
import { useGlobalStore } from '@/stores/global'

const router = useRouter()
const globalStore = useGlobalStore()

// 响应式数据
const selectedModel = ref('gpt-3.5-turbo')
const inputMessage = ref('')
const isLoading = ref(false)
const sessions = ref<AIChatSession[]>([])
const messages = ref<AIChatMessage[]>([])
const currentSessionId = ref<number | null>(null)
const showHistory = ref(true)
const modelOpen = ref(false)

// 快捷问题建议
const quickSuggestions = [
  '帮我解释这段代码的逻辑',
  '如何优化这个算法的时间复杂度？',
  '这个错误是什么原因导致的？',
  '推荐一些学习资源',
  '帮我写一个排序算法',
  '解释一下设计模式的应用场景'
]

// 计算属性
const getCurrentModelName = () => {
  const model = AI_MODELS.find(m => m.value === selectedModel.value)
  return model?.label || selectedModel.value
}

// 方法
const startNewChat = async () => {
  try {
    // 创建新的会话
    const response = await aiApi.createChatSession({
      title: '新对话',
      session_type: 'general'
    })
    
    if (response.data?.session) {
      currentSessionId.value = response.data.session.id
      messages.value = []
      inputMessage.value = ''
      
      // 刷新会话列表
      await loadSessions()
      
      globalStore.addToast({
        type: 'success',
        title: '新建对话',
        message: '已创建新的对话会话'
      })
    }
  } catch (error) {
    console.error('创建新会话失败:', error)
    globalStore.addToast({
      type: 'error',
      title: '创建失败',
      message: '无法创建新的对话会话'
    })
  }
}

const toggleHistory = () => {
  showHistory.value = !showHistory.value
}

const loadSession = async (sessionId: number) => {
  currentSessionId.value = sessionId
  try {
    const response = await aiApi.getChatMessages(sessionId)
    messages.value = response.data?.messages || []
  } catch (error) {
    console.error('加载会话消息失败:', error)
    globalStore.addToast({
      type: 'error',
      title: '加载对话失败',
      message: '无法加载该对话的历史消息'
    })
  }
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  const message = inputMessage.value.trim()
  inputMessage.value = ''
  isLoading.value = true

  try {
    const response = await aiApi.sendMessage({
      message,
      model: selectedModel.value,
      session_id: currentSessionId.value || undefined,
      session_type: 'general'
    })

    // 更新会话ID
    if (!currentSessionId.value) {
      currentSessionId.value = response.data?.session_id || null
    }

    // 添加用户消息
    messages.value.push({
      id: Date.now(),
      session_id: response.data?.session_id || 0,
      role: 'user',
      content: message,
      model: selectedModel.value,
      tokens: 0,
      created_at: new Date().toISOString()
    })

    // 添加AI回复
    messages.value.push({
      id: Date.now() + 1,
      session_id: response.data?.session_id || 0,
      role: 'assistant',
      content: response.data?.message || '',
      model: response.data?.model || selectedModel.value,
      tokens: response.data?.tokens || 0,
      created_at: new Date().toISOString()
    })

    // 刷新会话列表
    await loadSessions()
  } catch (error) {
    console.error('发送消息失败:', error)
    globalStore.addToast({
      type: 'error',
      title: '发送失败',
      message: '消息发送失败，请重试'
    })
  } finally {
    isLoading.value = false
  }
}

const sendQuickMessage = (message: string) => {
  inputMessage.value = message
  sendMessage()
}

const deleteSession = async (sessionId: number) => {
  try {
    await aiApi.deleteChatSession(sessionId)
    await loadSessions()
    
    if (currentSessionId.value === sessionId) {
      startNewChat()
    }
    
    globalStore.addToast({
      type: 'success',
      title: '删除成功',
      message: '对话已删除'
    })
  } catch (error) {
    console.error('删除会话失败:', error)
    globalStore.addToast({
      type: 'error',
      title: '删除失败',
      message: '无法删除该对话'
    })
  }
}

const loadSessions = async () => {
  try {
    const response = await aiApi.getChatSessions()
    sessions.value = response.data?.sessions || []
  } catch (error) {
    console.error('加载会话列表失败:', error)
  }
}

const formatTime = (timeStr: string) => {
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 1000 * 60) {
    return '刚刚'
  } else if (diff < 1000 * 60 * 60) {
    return `${Math.floor(diff / (1000 * 60))}分钟前`
  } else if (diff < 1000 * 60 * 60 * 24) {
    return `${Math.floor(diff / (1000 * 60 * 60))}小时前`
  } else {
    return date.toLocaleDateString()
  }
}

// 生命周期
onMounted(() => {
  loadSessions()
})
</script>

<style scoped>
/* 自定义滚动条 */
.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.space-y-6 > * {
  animation: fadeInUp 0.3s ease-out;
}

/* 模型选择下拉选项悬浮粉色背景 */
.model-select option:hover {
  background-color: #f472b6; /* Tailwind pink-400 */
  color: #ffffff;
}
</style>
